package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("redirect_url") String redirectUrl,
                          HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {

            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, username);

            // 登录完成之后，在当前域名下留下cookie值，表示之前有人曾登录过
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);

            // token 标记这次跳转是登录成功跳转过来的
            return "redirect:" + redirectUrl + "?token=" + uuid;
        }
        return "login";
    }

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url") String redirectUrl, Model model,
                        @CookieValue(value = "sso_token", required = false) String token) {

        // sso_token在第一个用户登录成功时，添加到ssoserver.com的cookie中
        // 之后其他域名过来访问的时候，只需要判断token是否有值，如果有值，说明该用户已经登录其他域名
        if (!StringUtils.isEmpty(token)) {
            return "redirect:" + redirectUrl + "?token=" + token;
        }

        model.addAttribute("redirect_url", redirectUrl);
        return "login";
    }
}
